import { Button } from "@/components/ui/button";
import { useTranslation } from "react-i18next";
import { Unlink, AlertCircle, type LucideProps, Mail } from "lucide-react";
import { useAccountBinding } from "@/hooks/use-account-binding";
import { cn } from "@/lib/utils";
import { SocailIcons } from "@/components/custom-ui/icons";
import { useUserStore } from "@/stores";
import type { Provider } from "@/types/oauth";

// 默认图标组件，用于处理懒加载失败的情况
const DefaultIcon = ({ className }: LucideProps) => (
  <div className={cn("w-8 h-8 bg-gray-200 rounded", className)} />
);

export function AccountBinding() {
  const { t } = useTranslation();
  const { user } = useUserStore();
  const {
    providers,
    isLoadingProviders,
    providersError,
    handleLinkAccount,
    handleUnlinkAccount,
    handleSetPrimaryEmail,
    isUnlinking,
    isSettingPrimaryEmail,
  } = useAccountBinding();

  if (isLoadingProviders) {
    return (
      <div className="flex items-center justify-center py-4">
        <div className="flex items-center gap-2">
          <div className="w-4 h-4 border-2 border-primary/20 border-t-primary rounded-full animate-spin"></div>
          <span className="text-primary/20">
            {t("Loading...", { defaultValue: "Loading..." })}
          </span>
        </div>
      </div>
    );
  }

  if (providersError) {
    return (
      <div className="flex items-center justify-center py-4">
        <div className="flex items-center gap-2 text-red-500">
          <AlertCircle className="w-4 h-4" />
          <span>
            {t("Failed to load account binding options", {
              defaultValue: "Failed to load account binding options",
            })}
          </span>
        </div>
      </div>
    );
  }

  if (providers.length === 0) {
    return (
      <div className="flex items-center justify-center py-4">
        <span className="text-primary/20">
          {t("No account binding options available", {
            defaultValue: "No account binding options available",
          })}
        </span>
      </div>
    );
  }

  // 分离已绑定和未绑定的提供商
  const linkedProviders = providers.filter(
    (provider) => provider.linked && provider.enabled
  );
  const allEnabledProviders = providers.filter((provider) => provider.enabled);

  return (
    <div className="space-y-4">
      {/* Account binding */}
      {allEnabledProviders.length > 0 && (
        <>
          <div className="text-sm font-medium text-muted-foreground mb-3">
            {t("Account binding", { defaultValue: "Account binding" })}
          </div>
          <div className="flex flex-wrap gap-4">
            {allEnabledProviders.map((provider, index) => {
              const IconComponent =
                SocailIcons[
                  (provider.provider.charAt(0).toLowerCase() +
                    provider.provider.slice(1)) as Provider
                ] || DefaultIcon;
              return (
                <IconComponent
                  key={index}
                  onClick={() =>
                    !provider.linked && handleLinkAccount(provider.provider)
                  }
                  className={cn(
                    "w-8 h-8",
                    provider.linked
                      ? "text-primary/40"
                      : "cursor-pointer text-primary hover:text-primary/60"
                  )}
                />
              );
            })}
          </div>
        </>
      )}

      {/* 已绑定的OAuth */}
      {linkedProviders.length > 0 && (
        <div>
          <div className="text-sm font-medium text-muted-foreground mb-3">
            {t("Bound accounts", { defaultValue: "Bound accounts" })}
          </div>
          <div className="space-y-3">
            {linkedProviders.map((provider, index) => {
              const IconComponent =
                SocailIcons[
                  (provider.provider.charAt(0).toLowerCase() +
                    provider.provider.slice(1)) as Provider
                ] || DefaultIcon;
              return (
                <div key={index} className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <IconComponent className="text-primary w-8 h-8" />
                    <div className="flex flex-col">
                      {provider.email ? (
                        <span className="text-sm">{provider.email}</span>
                      ) : (
                        <span className="text-sm text-primary/20">--</span>
                      )}
                      {provider.email && user && provider.email !== user.email && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleSetPrimaryEmail(provider.provider)}
                          disabled={isSettingPrimaryEmail}
                          className="h-6 px-1 text-xs hover:font-bold cursor-pointer"
                        >
                          <Mail className="w-3 h-3 mr-1" />
                          {isSettingPrimaryEmail
                            ? t("Setting...", { defaultValue: "Setting..." })
                            : t("Set as primary", { defaultValue: "Set as primary" })}
                        </Button>
                      )}
                    </div>
                  </div>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleUnlinkAccount(provider.provider)}
                    disabled={isUnlinking}
                    className="h-8 cursor-pointer"
                  >
                    <Unlink className="w-3 h-3 mr-1" />
                    {isUnlinking
                      ? t("Unlinking...", { defaultValue: "Unlinking..." })
                      : t("Unlink", { defaultValue: "Unlink" })}
                  </Button>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}
